<?php
/*
 * @Description: your project
 * @Author: xuyajun
 * @version: 1.0
 * @Date: 2023-06-05 15:01:20
 * @LastEditors: xuyajun
 * @LastEditTime: 2023-06-06 14:45:08
 */
declare (strict_types = 1);

namespace app\common\server;

use think\facade\Db;
use think\worker\Server;
use Workerman\Lib\Timer;
use app\common\server\HandleMsg;

// define('HEARTBEAT_TIME', 30);// 心跳间隔
class Worker extends Server
{
	protected $socket = 'websocket://0.0.0.0:2346';
	
    // 服务启动时
	public function onWorkerStart($worker) {
		(new HandleMsg())->heartCheck($worker);
	}

	public function onConnect($connection) {
		
	}

    // 监听到消息
	public function onMessage($connection, $data) {
		#最后接收消息时间
		$connection->lastMessageTime = time();
		
		$msg_data = json_decode($data, true);
		if (!$msg_data){
			return;
		}

		switch($msg_data['type']){
			case "bind": // 绑定客户端id
				(new HandleMsg())->bindUid($connection, $this->worker, $msg_data);
				return;
			case "say": // 发送文本/表情消息 
				(new HandleMsg())->sendTextOrEmoji($this->worker, $msg_data);
				return;
			case "say_img": // 发送图片消息
				(new HandleMsg())->sendImage($this->worker, $msg_data);
				return;
			case "online": // 在线状态
				(new HandleMsg())->sendOnlineStatus($this->worker, $msg_data);
				return;
		}

		// #绑定用户ID
		// if ($msg_data['type'] == 'bind' && !isset($connection->uid)){
		// 	$connection->uid = $msg_data['uid'];
		// 	$this->worker->uidConnections[$connection->uid] = $connection;
		// }
		
		
		// Db::name('online_customer_service')->insert();
		
		// #单人发消息
		// if ($msg_data['type'] == 'text' && $msg_data['mode'] == 'single'){
		// 	if (isset($this->worker->uidConnections[$msg_data['to_id']])){
		// 		$conn = $this->worker->uidConnections[$msg_data['to_id']];
		// 		$conn->send($data);
		// 	}
		// }
		// #群聊
		// if ($msg_data['type'] == 'text' && $msg_data['mode'] == 'group'){
		// 	#实际项目通过群号查询群里有哪些用户
		// 	$group_user = [10009,10010,10011,10012,10013,10014,10015,10016,10017];
		// 	foreach ($group_user as $key => $val){
		// 		if (isset($this->worker->uidConnections[$val])){
		// 			$conn = $this->worker->uidConnections[$val];
		// 			$conn->send($data);
		// 		}
		// 	}
		// }
		
		// #向所有用户发送消息
		// foreach ($this->worker->connections as $key => $con){
		// 	$con->send($data);
		// }
		
		// $connection->send(json_encode($data));
		// $connection->send($data);
	}
	
}